import { useNavigate, useSearchParams } from "react-router-dom";
import styles from "./index.module.css";
import {
  ActionSheet,
  //   Avatar,
  Button,
  Form,
  Input,
  NavBar,
  Toast,
} from "antd-mobile";
import { useEffect, useRef, useState } from "react";
import Pouops from "../../../component/pouop";
import request from "../../../axios";
const SalesEdit = () => {
  const navigate = useNavigate();
  const [searParams] = useSearchParams();
  const [form]: any = Form.useForm();

  const type: string = searParams.get("type") || "";
  const handler = useRef<any>(null);
  const [status, setStatus] = useState<string>("open");
  const [visible, setVisible] = useState<boolean>(false);
  const [formIs, setFormIs] = useState<boolean>(false);
  const [headerList, setHeader] = useState<any[]>([]);

  const actions: any[] = [
    {
      text: "启用",
      key: "open",
      onClick: () => {
        setStatus("open");
        handler.current?.close();
      },
    },
    {
      text: "停用",
      key: "close",
      onClick: () => {
        setStatus("close");
        handler.current?.close();
      },
    },
  ];

  const getUserList = async () => {
    try {
      const { data } = await request.get("/store/list", {
        pageNo: 1,
        pageSize: 999,
      });
      if (data) {
        setHeader(data?.records || []);
        if (searParams.get("type") === "edit") {
          setFormIs(true);
        }
      }
    } catch (error) {}
  };

  const handleSubmit = async (val: any) => {

    const id = searParams.get("type") === 'edit' ? JSON.parse(searParams.get('info') || '{}')?.id : null;
    const url = searParams.get("type") === 'edit' ? '/dish/update' : '/dish/create';

    try {
      await request.post(url, {
        id,
        name: val?.name,
        status: status === "open" ? 1 : 0,
        storeId: headerList.some((item) => item.checked)
          ? headerList
              .filter((item: any) => item.checked)
              .map((item: any) => item.id)
              .join(",")
          : null,
      });
      Toast.show("提交成功");
    } catch (error) {}
    navigate(-1);
  };

  const setFormVal = () => {
    const info = JSON.parse(searParams.get("info") || "{}");
    form.setFieldsValue({
      ...info
    });

    setStatus(info.status ? "open" : "")
    setHeader(headerList.map((item) => {
        return {
            ...item,
            checked: info.storeId?.split(",").includes(String(item.id))
        }
    }))
  };

  useEffect(() => {
    getUserList();
  }, []);

  useEffect(() => {
    setFormVal();
  }, [formIs]);

  return (
    <div className={styles.content}>
      <NavBar
        onBack={() => {
          navigate(-1);
        }}
        style={{ padding: "8px 20px" }}
      >
        {type === "add" ? "添加菜谱" : "编辑菜谱"}
      </NavBar>
      <Form
        layout="horizontal"
        mode="card"
        form={form}
        onFinish={(val) => {
          handleSubmit(val);
        }}
        footer={
          <div
            style={{
              width: "100%",
              display: "flex",
              justifyContent: "space-around",
              alignItems: "center",
              height: "60px",
            }}
          >
            <Button
              block
              type="submit"
              color="primary"
              size="large"
              className={styles.subbtn}
            >
              确认{type === "add" ? "新增" : "编辑"}
            </Button>
          </div>
        }
      >
        <Form.Item name="code" label="菜谱编码" className={styles.input_title}>
          <Input onChange={console.log} placeholder="请输入菜谱编码" disabled />
        </Form.Item>
        <Form.Item name="name" label="菜谱名称" className={styles.input_title}>
          <Input onChange={console.log} placeholder="请输入菜谱名称" />
        </Form.Item>
        <Form.Item
          name="shopName"
          label="使用门店"
          className={styles.input_title}
          onClick={() => {
            setVisible(true);
          }}
        >
          {headerList?.some((item: any) => item.checked) ? (
            headerList
              .filter((item: any) => item.checked)
              .map((item: any) => item.name)
              .join(",")
          ) : (
            <span className={styles.default}>请选择适用门店</span>
          )}
        </Form.Item>
        <Pouops
          data={headerList}
          setData={setHeader}
          value={visible}
          setValue={setVisible}
          type="checkbox"
        />
        <Form.Item
          name="status"
          label="菜谱状态"
          trigger="onConfirm"
          className={styles.input_title}
          onClick={() => {
            handler.current = ActionSheet.show({
              actions: actions,
              cancelText: "取消",
              onClose: () => {
                // Toast.show("动作面板关闭");
              },
            });
          }}
        >
          {status === "open" ? "启用" : "停用"}
        </Form.Item>
      </Form>
    </div>
  );
};

export default SalesEdit;
